package com.mypage.view.activity.beautMore;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.impl.BeauInfoShareSet;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.fragment.BeauListFragmentType;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.adapter.NchangeListAdapter;
import com.mypage.bean.RelatedListBean;
import com.mypage.bean.UpdatePersonBean;
import com.mypage.utils.UtilsShowDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChangePersonActivity extends Activity {
    public NchangeListAdapter mAdapter;
    public List<RelatedListBean.RelatedData.mRelatedList> mList;
    //    public List<RelatedListBean.data.relatedlist> mList;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    public String mPname;
    public String mObjId;
    public String mObjName;
    public String mEntityNameIDs;
    public String mEntityIds;
    public String mPersionName;
    public String mPersionNameIds;

    public String OwerName;
    public String OwerNameID;


    public String mData;
    @Bind(R.id.btnImgBack)
    ImageView btnImgBack;
    @Bind(R.id.btnImgRight)
    ImageView btnImgRight;
    @Bind(R.id.etSearchContent)
    Button etSearchContent;
    @Bind(R.id.imgDelete)
    ImageView imgDelete;
    @Bind(R.id.imgDeletes)
    ImageView imgDeletes;
    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;
    @Bind(R.id.listCheck)
    ListView listCheck;
    @Bind(R.id.chEmain)
    CheckBox chEmain;
    public boolean mEmail;
    public boolean mState = true;
    public String Ids;
    @Bind(R.id.textListtext)
    TextView textListtext;
    @Bind(R.id.toastHintContent)
    TextView toastHintContent;
    private UtilsShowDialog showDialog;
    private String mStrRelated;

    private AlphaAnimation appearAnimator;
    private AlphaAnimation appearAnimator2;
    private AlphaAnimation disappearAnimator;
    private AlphaAnimation disappearAnimator2;
    public int ts = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_person);
        ButterKnife.bind(this);
        showDialog = new UtilsShowDialog(this);
        mEntityNameIDs = getIntent().getStringExtra("mEntityNameIDs");
        mEntityIds = getIntent().getStringExtra("mEntityNameIDs");

        mPersionName = getIntent().getStringExtra("mPersionName");
        mPersionNameIds = getIntent().getStringExtra("mPersionNameIds");

        OwerName = getIntent().getStringExtra("OwerName");
        OwerNameID = getIntent().getStringExtra("OwerNameID");

        getDataHttp();//相关列表
        initData();
        initListenr();
    }

    public void initData() {


        mPname = getIntent().getStringExtra("mPname");
        mObjId = getIntent().getStringExtra("mObjId");
        mObjName = getIntent().getStringExtra("mObjName");
        Log.d("mObjId=",getIntent().getStringExtra("mObjId")+"    mObjName="+getIntent().getStringExtra("mObjName"));
        etSearchContent.setText(OwerName);
        appearAnimator = new AlphaAnimation(0, 1);
        appearAnimator.setDuration(ts);
        appearAnimator2 = new AlphaAnimation(0, 1);
        appearAnimator2.setDuration(ts);
        disappearAnimator = new AlphaAnimation(1, 0);
        disappearAnimator.setDuration(ts);
        disappearAnimator2 = new AlphaAnimation(1, 0);
        disappearAnimator2.setDuration(ts);
    }

    public void initListenr() {
        chEmain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (mState) {
                    mEmail = true;//表示发邮件
                    mState = false;
                } else {
                    mEmail = false;//不发邮件
                    mState = true;
                }
            }
        });
        listCheck.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NchangeListAdapter.HolderView h = (NchangeListAdapter.HolderView) view.getTag();
//                cancelCH();//单选开关
                if (h.checkBox.isChecked()) {
                    NchangeListAdapter.getIsSelected().put(position, false);
//                    h.checkBox.setBackgroundResource(R.drawable.personchtwo);
                    mStrRelated += mList.get(position).fieldId + ",";
                    if (mStrRelated.contains(mList.get(position).fieldId)) {
                        mStrRelated.replace(mList.get(position).fieldId + ",", "");
                    }
                } else {
                    NchangeListAdapter.getIsSelected().put(position, true);
                    mStrRelated += mList.get(position).fieldId + ",";
//                    h.checkBox.setBackgroundResource(R.drawable.personchone);
                }

                mAdapter.notifyDataSetChanged();

            }
        });
    }

    @OnClick({R.id.btnImgBack, R.id.btnImgRight, R.id.imgDelete, R.id.imgDeletes})
    public void setBtn(ImageView b) {
        switch (b.getId()) {
            case R.id.btnImgBack:
                finish();
                break;
            case R.id.btnImgRight:
                // TODO: 2017/5/9
                showDialog.onShowLoadingDialog("正在更新...");
                updateData();
//                if (mEmail) {
//                    sendEmain();//发邮件
//                    finish();
//                }else{
//                    // TODO: 2017/5/19  不发邮件
//                }
                break;
            case R.id.imgDelete:
                etSearchContent.setText("");
                break;
            case R.id.imgDeletes:
//                layoutTop.setVisibility(View.GONE);
                setHintToast();
                break;

        }
    }

    @OnClick(R.id.etSearchContent)
    public void etSearchContent() {
        Intent intent = new Intent(this, NewInputNameActivity.class);
        if ("en".equals(mEns)) {
            intent.putExtra("User","Enter the new owner name");
        } else {
            intent.putExtra("User","输入新所有人名称");
        }

        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (data == null)
                return;
            String mName = data.getStringExtra("Name");
            mObjId = data.getStringExtra("mId");
            OwerNameID = data.getStringExtra("mId");
            etSearchContent.setText(mName);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void getDataHttp() {
        showDialog.onShowLoadingDialog("正在加载...");
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "queryRelatedListCountApp");
        params.addBodyParameter("recordId", mPersionNameIds);
        params.addBodyParameter("objId", mEntityIds);
        Log.d("request相关列表url", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding() + "&serviceName=" +
                "queryRelatedListCountApp&" + "recordId=" + mEntityNameIDs + "&objId=" + mEntityIds);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Log.d("request相关列表Fail", arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Log.d("request相关列表Success", arg0.result.toString());
                RelatedListBean mData = new Gson().fromJson(arg0.result.toString(), RelatedListBean.class);
                mList = mData.data.relatedlist;
                if (mList == null) {
                    textListtext.setVisibility(View.INVISIBLE);
                    showDialog.onDismissLoadingDialog();
                    return;
                }
                textListtext.setVisibility(View.VISIBLE);
                mAdapter = new NchangeListAdapter(mList, ChangePersonActivity.this);
                listCheck.setAdapter(mAdapter);
                showDialog.onDismissLoadingDialog();
            }
        });

    }


    public void sendEmain() {
        createJson();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "sendEmail");
        params.addBodyParameter("data", mData);
        Log.d("发送邮件url----------", UrlManager.getInterfaceUrl() + "?" + "binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=sendEmail&" + "data=" + mData);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    // 把数据转换成json格式。用于上传服务端
    public void createJson() {
        JSONObject object = new JSONObject();
        try {
            object.put("toAddress", "656864464@qq.com");//收件人
            object.put("subject", "更改所有人");//主题
            object.put("content", "你好，已经设置为您更改所人");
            mData = object.toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void cancelCH() {
//        for (int i = 0; i < mList.size(); i++) {
//            if (NchangeListAdapter.getIsSelected().get(i)) {
//                NchangeListAdapter.getIsSelected().put(i, false);
//
//            }
//        }
    }

    public void updateData() {
        if (mStrRelated!=null)
        mStrRelated = mStrRelated.replace("null","").substring(0,mStrRelated.replace("null","").length()-1);
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "updatRecordOwner");
        params.addBodyParameter("objId", mEntityNameIDs);//对象id
        params.addBodyParameter("recordname", mPersionName);//记录名称
        params.addBodyParameter("recordId", mPersionNameIds);//记录id
        params.addBodyParameter("sendMail", String.valueOf(mEmail));//是否发送邮件
        params.addBodyParameter("newOwnerId", OwerNameID);//新所有人
        params.addBodyParameter("relatedids", mStrRelated);//相关列表字段id 如：relatedids=ffe2017B65130AFbIkSH,task1,task2
        Log.d("request更新所有人url", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding() + "&serviceName=updatRecordOwner&objId=" + mEntityNameIDs + "&recordname=" + mPersionName + "&sendMail=" + String.valueOf(mEmail) + "&recordId=" + mPersionNameIds + "&newOwnerId=" + mObjId + "&relatedids=" + mStrRelated);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.d("request更新所有人Success", "异常类型" + arg0.toString() + "；；；失败信息" + arg1);
                showDialog.onDismissLoadingDialog();
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                Log.d("request更新所有人Success", arg0.result.toString());

                UpdatePersonBean mCallBackData = new Gson().fromJson(arg0.result.toString(), UpdatePersonBean.class);
                String mToastStr = mCallBackData.data.updateResult.get(0).updateResultInfo;
                if (mToastStr.contains("已变更为新所有人")){
                    if (mCallBackData.data.updateResult.get(0).updateRP){
                        BeauInfoShareSet.getInstance().setChangeDao(mToastStr);
                    }else{
//                        BeauListFragmentType.setToastStr(mToastStr);
//                        BeauInfoActivity.inatance.finish();
                    }

                    finish();
                }else{
                    toastHintContent.setText(mToastStr);
                    appearToast();
                    setHintToast();
                }


//                finish();

            }
        });
    }

    /**
     * 显示Toast
     */
    public void appearToast() {
        showDialog.onDismissLoadingDialog();
        if (layoutTop.getVisibility() == View.GONE) {
            layoutTop.startAnimation(appearAnimator);
            layoutTop.setVisibility(View.VISIBLE);
        }
       for (int i=0;i<100000;i++){

       }
    }

    /**
     * 隐藏Toast
     */
    public void setHintToast() {
        for (int i = 0;i<100000;i++){

        }
        if (layoutTop.getVisibility() == View.VISIBLE) {
            hideRlBack(layoutTop, disappearAnimator2);
        }
    }

    /**
     * 控制渐进式隐藏布局
     */
    private void hideRlBack(final FrameLayout rl, AlphaAnimation disappearAnimator) {
        rl.startAnimation(disappearAnimator);
        disappearAnimator.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                rl.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


}
